package com.yyy.tcc.service.compensation;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.sql.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class AlertService {
    private static final Logger log = LoggerFactory.getLogger(AlertService.class);
    private final DataSource dataSource;

    public AlertService(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    /**
     * 记录告警
     */
    public void recordAlert(String transactionId, String alertType, String title, String message) {
        String sql = "INSERT INTO alert_record (transaction_id, alert_type, title, message, status) " +
                    "VALUES (?, ?, ?, ?, 'NEW')";

        try (Connection conn = dataSource.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, transactionId);
            pstmt.setString(2, alertType);
            pstmt.setString(3, title);
            pstmt.setString(4, message);

            pstmt.executeUpdate();

            // 发送实时通知
            sendNotification(title, message);

        } catch (SQLException e) {
            log.error("记录告警失败: {}", transactionId, e);
        }
    }

    /**
     * 获取未处理的告警
     */
    public List<AlertRecord> getUnresolvedAlerts() {
        List<AlertRecord> alerts = new ArrayList<>();
        String sql = "SELECT * FROM alert_record WHERE status = 'NEW' ORDER BY create_time DESC";

        try (Connection conn = dataSource.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                AlertRecord alert = new AlertRecord();
                alert.setId(rs.getLong("id"));
                alert.setTransactionId(rs.getString("transaction_id"));
                alert.setAlertType(rs.getString("alert_type"));
                alert.setTitle(rs.getString("title"));
                alert.setMessage(rs.getString("message"));
                alert.setStatus(rs.getString("status"));
                alert.setCreateTime(rs.getTimestamp("create_time").toLocalDateTime());
                alerts.add(alert);
            }

        } catch (SQLException e) {
            log.error("获取未处理告警失败", e);
        }

        return alerts;
    }

    /**
     * 更新告警状态
     */
    public void updateAlertStatus(long alertId, String status) {
        String sql = "UPDATE alert_record SET status = ? WHERE id = ?";

        try (Connection conn = dataSource.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, status);
            pstmt.setLong(2, alertId);
            pstmt.executeUpdate();

        } catch (SQLException e) {
            log.error("更新告警状态失败: {}", alertId, e);
        }
    }

    /**
     * 发送实时通知
     */
    private void sendNotification(String title, String message) {
        // 这里可以集成各种通知方式：
        // 1. 发送邮件
        // sendEmail(title, message);

        // 2. 发送短信
        // sendSMS(title, message);

        // 3. 发送钉钉消息
        // sendDingTalkMessage(title, message);

        // 4. 记录日志
        log.warn("告警通知: {} - {}", title, message);
    }

    /**
     * 告警记录实体类
     */
    public static class AlertRecord {
        private Long id;
        private String transactionId;
        private String alertType;
        private String title;
        private String message;
        private String status;
        private LocalDateTime createTime;

        // Getters and Setters
        public Long getId() { return id; }
        public void setId(Long id) { this.id = id; }

        public String getTransactionId() { return transactionId; }
        public void setTransactionId(String transactionId) { this.transactionId = transactionId; }

        public String getAlertType() { return alertType; }
        public void setAlertType(String alertType) { this.alertType = alertType; }

        public String getTitle() { return title; }
        public void setTitle(String title) { this.title = title; }

        public String getMessage() { return message; }
        public void setMessage(String message) { this.message = message; }

        public String getStatus() { return status; }
        public void setStatus(String status) { this.status = status; }

        public LocalDateTime getCreateTime() { return createTime; }
        public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; }
    }
}
